package com.xteam.xnetworkdisk.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xteam.xnetworkdisk.sys.entity.LocationResponse;
import com.xteam.xnetworkdisk.utilsinterface.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Slf4j
public class IPIp2RegionUtils implements IPUtils {

    private static Searcher searcher;

    static {
        // 静态代码块中初始化 Searcher 对象
        try (InputStream dbInputStream = IPIp2RegionUtils.class.getClassLoader().getResourceAsStream("static/ip2region.xdb")) {
            if (dbInputStream == null) {
                throw new RuntimeException("IP database file not found.");
            }
            byte[] cBuff = dbInputStream.readAllBytes();
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (IOException e) {
            log.error("Failed to initialize Searcher: ", e);
            throw new RuntimeException("Failed to load IP database.", e);
        }
    }

    @Override
    public String getClientIpAddress(HttpServletRequest request) {
        // 获取客户端IP地址，考虑多种头部字段
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getHeader("X-Real-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    @Override
    public String getLocationByIp(String ip) {

        LocationResponse locationResponse = new LocationResponse();
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            locationResponse.setStatus("fail");  // country: "中国"
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.writeValueAsString(locationResponse);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        // 查询并记录性能
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
            log.info("{region: {}, ioCount: {}, took: {} μs}", region, searcher.getIOCount(), cost);

            // 解析查询结果并构建 LocationResponse 对象
            String[] parts = region.split("\\|");
            if (parts.length != 5) {
                throw new IllegalArgumentException("Unexpected region format: " + region);
            }

            String country = parts[0];

            if (country.equals("0")) {
                locationResponse.setStatus("fail");  // country: "中国"
            } else {
                locationResponse.setStatus("success");  // country: "中国"
            }

            locationResponse.setCity(parts[3]);  // city: "宜昌市"
            locationResponse.setRegionName(parts[2]);  // regionName: "湖北省"
            locationResponse.setCountry(country);  // country: "中国"

            // 将 LocationResponse 对象转换为 JSON 字符串
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(locationResponse);
        } catch (Exception e) {
            log.error("Failed to search({}): ", ip, e);
            return null;
        }
    }

    public String getDeviceDetails(HttpServletRequest request) {
        // 获取 User-Agent 信息
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "Unknown Device";
        }

        String deviceDetails = "Unknown Device";
        if (userAgent.contains("Windows")) {
            deviceDetails = "Windows";
        } else if (userAgent.contains("Mac")) {
            deviceDetails = "Mac";
        } else if (userAgent.contains("X11")) {
            deviceDetails = "Unix";
        } else if (userAgent.contains("Android")) {
            deviceDetails = "Android";
        } else if (userAgent.contains("iPhone")) {
            deviceDetails = "iPhone";
        }

        // 解析更多信息（浏览器、版本等）可以继续扩展

        return deviceDetails;
    }
}
